<?php

namespace ProjetA\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use JMS\SecurityExtraBundle\Annotation\Secure;
use FOS\UserBundle\Model\UserInterface;


class UtilisateurController extends Controller
{
    /**
     * Display all users
     * @Secure(roles="ROLE_ADMIN")
     */
    public function indexAction()
    {
        $userManager = $this->get('fos_user.user_manager');
        $users = $userManager->findUsers();
        return $this->render('ProjetAAdminBundle:Utilisateur:index.html.twig', array('users' => $users));
    }
    
    /**
     * Display all users
     * @Secure(roles="ROLE_ADMIN")
     */
    public function bannirAction($username)
    {
        $userManager = $this->get('fos_user.user_manager');
        $user = $userManager->findUserBy(array('username' => $username));
        if($user->isEnabled()){
            $user->setEnabled(FALSE);
            $this->get('session')->setFlash('message', 'admin.user.ban');
        }
        else{
            $user->setEnabled(TRUE);
            $this->get('session')->setFlash('message', 'admin.user.deban');
        }
        $userManager->updateUser($user);        
        return $this->redirect($this->generateUrl('ProjetAAdminBundle_user'));
    }
    
    public function adminAction($username)
    {
        $userManager = $this->get('fos_user.user_manager');
        $user = $userManager->findUserBy(array('username' => $username));
        if($user->hasRole("ROLE_ADMIN")){
            $user->removeRole("ROLE_ADMIN");
            $this->get('session')->setFlash('message', 'admin.user.utilisateur');
        }
        else{
            $user->addRole("ROLE_ADMIN");
            $this->get('session')->setFlash('message', 'admin.user.admin');
        }
        $userManager->updateUser($user);        
        return $this->redirect($this->generateUrl('ProjetAAdminBundle_user'));
    }
    
}
